JavaScript syntax
part 2/31 Β· 107.4 KB total
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Origins
Brendan Eich summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specificationcite-ref-1[1]cite-ref-2[2] as follows:
Basics
Case sensitivity
JavaScript is case sensitive. It is common to start the name of a constructor with a capitalized letter, and the name of a function or variable with a lower-case letter.
Example:
var a = 5;
console.log(a); // 5
console.log(A); // throws a ReferenceError: A is not defined
Whitespace and semicolons
Unlike in C, whitespace in JavaScript source can directly impact semantics. Semicolons end statements in JavaScript. Because of automatic semicolon insertion (ASI), some statements that are well formed when a newline is parsed will be considered complete, as if a semicolon were inserted just prior to the newline. Some authorities advise supplying statement-terminating semicolons explicitly, because it may lessen unintended effects of the automatic semicolon insertion.cite-ref-3[3]
There are two issues: five tokens can either begin a statement or be the extension of a complete statement; and five restricted productions, where line breaks are not allowed in certain positions, potentially yielding incorrect parsing.
The five problematic tokens are the open parenthesis "(", open bracket "[", slash "/", plus "+", and minus "-". Of these, the open parenthesis is common in the immediately invoked function expression pattern, and open bracket occurs sometimes, while others are quite rare. An example:
a = b + c
(d + e).foo()
// Treated as:
// a = b + c(d + e).foo();
with the suggestion that the preceding statement be terminated with a semicolon.
Some suggest instead the use of leading semicolons on lines starting with '(' or '[', so the line is not accidentally joined with the previous one. This is known as a defensive semicolon, and is particularly recommended, because code may otherwise become ambiguous when it is rearranged. For example:
a = b + c
;(d + e).foo()
// Treated as:
// a = b + c;
// (d + e).foo();
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ